package org.example.juc.sync;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 3;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1000); // 模拟工作
                    System.out.println("Thread finished.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown(); // 完成工作，计数减一
                }
            }).start();
        }

        latch.await(); // 等待所有线程完成
        System.out.println("All threads finished.");
    }
}
